const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database();

exports.main = async (event, context) => {
    try {
      const { data } = await db.collection('user').where({
        studentid: event.studentid,
        password: event.password,
        role: event.role
      }).get()
      if (data.length) {
        return {
          success: 'ok',
          msg: '登录成功'
        }
      } else {
        return {
          success: 'error',
          msg: '学号错误或密码错误'
        }
      }
    } catch(e) {
      return {
        status: 0,
        msg: e
      }
    }
}

exports.register = async (event, context) => {
    try {
      const { data } = await db.collection('user').where({
        studentid: event.studentid
      }).get()
      if (data.length) {
        return {
          success: 'error',
          msg: '学号已注册'
        }
      } else {
        await db.collection('user').add({
          data: {
            studentid: event.studentid,
            password: event.password
          }
        })
        return {
          success: 'ok',
          msg: '注册成功'
        }
      }
    } catch (e) {
      return {
        success: 'error',
        msg: '注册失败'
      }
    }
}